package net.youpo.Market.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import net.youpo.Market.MarketApplication;
import net.youpo.Market.Bean.AppInfoBean;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class DeviceInfo {
	/*
	 * 获取当前程序的版本号
	 */
	public static int getMyVersionCode() {
		PackageInfo pinfo;
		try {
			pinfo = MarketApplication
					.getMarketAppContext()
					.getPackageManager()
					.getPackageInfo("net.youpo.Market",
							PackageManager.GET_CONFIGURATIONS);
			return pinfo.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 获取安装的应用程序信息
	 */
	public static ArrayList<AppInfoBean> getInstallAppInfo() {
		ArrayList<AppInfoBean> appList = new ArrayList<AppInfoBean>(); // 用来存储获取的应用信息数据
		PackageManager pm = MarketApplication.getMarketAppContext()
				.getPackageManager();
		List<PackageInfo> packages = pm.getInstalledPackages(0);

		for (int i = 0; i < packages.size(); i++) {
			PackageInfo packageInfo = packages.get(i);
			AppInfoBean tmpInfo = new AppInfoBean();
			tmpInfo.APP_NAME = packageInfo.applicationInfo.loadLabel(pm)
					.toString();
			tmpInfo.APP_PACK = packageInfo.packageName;
			tmpInfo.APP_VER_NAME = packageInfo.versionName;
			tmpInfo.APP_VER = packageInfo.versionCode;
			tmpInfo.APP_ICON_BMP = packageInfo.applicationInfo.loadIcon(pm);
			// Only display the non-system app info
			if (((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
					&& !tmpInfo.APP_PACK.equals(MarketApplication
							.getMarketAppContext().getPackageName())) {// 如果非系统应用，则添加至appList
				appList.add(tmpInfo);
			}
		}
		return appList;
	}

	/**
	 * 获取使用频率
	 */
	public static long getAppUseTimes() {
		SharedPreferences sPreferences = PreferenceManager
				.getDefaultSharedPreferences(MarketApplication
						.getMarketAppContext());
		long useTimes = sPreferences.getInt(ConstantsTable.USE_TIMES, 0);
		return useTimes;
	}

	/**
	 * 获得手机品牌
	 * 
	 * @return
	 */
	public static String getDeviceManufacturer() {
		return android.os.Build.MANUFACTURER;
	}

	/**
	 * 获得手机型号
	 * 
	 * @return
	 */
	public static String getDeviceModel() {
		return android.os.Build.MODEL;
	}

	/**
	 * 获取IMEI
	 * 
	 * @return
	 */
	public static String getDeviceIMEI() {
		TelephonyManager telephonyManager = (TelephonyManager) MarketApplication
				.getMarketAppContext().getSystemService(
						Context.TELEPHONY_SERVICE);
		return telephonyManager.getDeviceId();
	}

	/**
	 * 获取手机号
	 * 
	 * @return
	 */
	public static String getDevicePhoneNumber() {
		TelephonyManager telephonyManager = (TelephonyManager) MarketApplication
				.getMarketAppContext().getSystemService(
						Context.TELEPHONY_SERVICE);
		return telephonyManager.getLine1Number();
	}

	/**
	 * 获取运营商名称
	 * 
	 * @return
	 */
	public static String getDeviceOperatorName() {
		TelephonyManager telephonyManager = (TelephonyManager) MarketApplication
				.getMarketAppContext().getSystemService(
						Context.TELEPHONY_SERVICE);
		return telephonyManager.getNetworkOperatorName();
	}

	/**
	 * 获取本软件安装时间
	 * 
	 * @return
	 */
	public static String getAppInstallTime() {
		SharedPreferences sPreferences = PreferenceManager
				.getDefaultSharedPreferences(MarketApplication
						.getMarketAppContext());
		long installTime = sPreferences.getLong(ConstantsTable.INSTALL_TIME, 0);
		SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 格式化当前系统日期
		String dateTime = dateFm.format(new Date(installTime));
		return dateTime;
	}

	/**
	 * 获取地址
	 * 
	 * @return
	 */
	public static String getDeviceAddressbyGeoPoint() {
		// 自经纬度取得地址
		LocationManager locationManager = (LocationManager) MarketApplication
				.getMarketAppContext().getSystemService(
						Context.LOCATION_SERVICE);
		Location location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location == null) {
			location = locationManager
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);// 如果gps取不到就取网络的
		}
		// Log.d("H3c",
		// "k:" + location.getLatitude() + "-" + location.getLongitude());
		String add = GetAddr(String.valueOf(location.getLatitude()),
				String.valueOf(location.getLongitude()));
		if (add != null) {
			return add;
		}
		return location.getLatitude() + "-" + location.getLongitude();
	}

	/**
	 * 根据经纬度反向解析地址，有时需要多尝试几次
	 * 注意:(摘自：http://code.google.com/intl/zh-CN/apis/maps/faq.html
	 * 提交的地址解析请求次数是否有限制？) 如果在 24 小时时段内收到来自一个 IP 地址超过 2500 个地址解析请求， 或从一个 IP
	 * 地址提交的地址解析请求速率过快，Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多，则从该 IP
	 * 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。
	 * 
	 * @param latitude
	 *            纬度
	 * @param longitude
	 *            经度
	 * @return
	 */
	private static String GetAddr(String latitude, String longitude) {
		String addr = "";
		// 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s，不过解析出来的是英文地址
		// 密钥可以随便写一个key=abc
		// output=csv,也可以是xml或json，不过使用csv返回的数据最简洁方便解析
		String url = String.format(
				"http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
				latitude, longitude);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}

		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					String[] retList = data.split(",");
					if (retList.length > 2 && ("200".equals(retList[0]))) {
						addr = retList[2];
						addr = addr.replace("\"", "");
					} else {
						addr = "";
					}
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return addr;
	}
}
